package com.rjwh.dingdong.client.activity.radio;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aishua.lib.utils.AsStrUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.activity.player.fragment.PlayerToolbarFragment;
import com.rjwh.dingdong.client.adapter.RadioAlbumProgramListAdapter;
import com.rjwh.dingdong.client.bean.localbean.PlayList;
import com.rjwh.dingdong.client.bean.localbean.RadioAnchorInfo;
import com.rjwh.dingdong.client.bean.localbean.Song;
import com.rjwh.dingdong.client.mvp.presenter.impl.RadioAlbumProgramPresenter;
import com.rjwh.dingdong.client.mvp.view.RadioAlbumProgramView;
import com.rjwh.dingdong.client.player.IPlayback;
import com.rjwh.dingdong.client.player.PlayConstants;
import com.rjwh.dingdong.client.player.PlayState;
import com.rjwh.dingdong.client.service.PlaybackService;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.RxBus;
import com.rjwh.dingdong.client.util.StatusBarUtils;
import com.rjwh.dingdong.client.view.PullToZoomListView;
import com.rjwh.dingdong.client.widget.RoundImageView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * @author Kay
 * @ClassName RadioAlbumProgramActivity
 * @Description 主播节目列表
 * @date 2016-10-26
 * @history 2016-10-26 author: description:
 */
public class RadioAlbumProgramActivity extends BaseActivity implements RadioAlbumProgramView, AbsListView.OnScrollListener {

    @BindView(R.id.radio_album_program_list)
    PullToZoomListView radioAlbumList;
    @BindView(R.id.transparency_toolbar)
    Toolbar toolbar;
    @BindView(R.id.loading_layout)
    RelativeLayout loadingLayout;
    @BindView(R.id.error_layout)
    RelativeLayout errorLayout;
    @BindView(R.id.transparency_app_bar_layout)
    AppBarLayout transparencyAppBarLayout;

    private RadioAlbumProgramListAdapter adapter;
    private String anchorid;
    private String albumid;

    private RadioAlbumProgramPresenter presenter;
    private Observable<Song> observableUpdateSong;
    private Observable<PlayState> observablePlayState;
    private IPlayback mPlayer;
    private int currentIndex = -1;
    private PlayList playList = new PlayList();
    private RoundImageView radioAlbumProgramAvatarImg;
    private TextView radioAlbumProgramNameTv;
    private TextView radioAlbumProgramPlayTimesTv;
    private TextView radioAlbumProgramFansTv;
    private ImageView radioAlbumProgramBannerFollowBtn;
    //测量值
    private float headerHeight;//顶部banner高度
    private float minHeaderHeight;//顶部最低高度，即Bar的高度
    private String radioname;
    private String albumname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.radio_album_program_layout);
        ButterKnife.bind(this);
        parseIntent();
        initObserver();
        initMeasure();
        initView();

        presenter = new RadioAlbumProgramPresenter(this, this);
        presenter.subscribe();
        doGetRadioAlbumProgram();
    }


    private void initObserver() {
        observableUpdateSong = RxBus.get().register(PlayConstants.ACTION_UPDATA_SONG, Song.class);
        observablePlayState = RxBus.get().register(PlayConstants.ACTION_PLAY_STATUS_CHANGED, PlayState.class);
        addSubscription(observableUpdateSong, subscriberUpdateSong);
        addSubscription(observablePlayState, subscriberPlayState);
    }

    private void doGetRadioAlbumProgram() {
        hideErrorView();
        showLoadingView();
        presenter.doGetRadioAlbumProgramList(anchorid, albumid);
    }

    public static void startActivity(Context context, String anchorid, String albumid, String albumname) {
        Intent intent = new Intent(context, RadioAlbumProgramActivity.class);
        intent.putExtra("anchorid", anchorid);
        intent.putExtra("albumid", albumid);
        context.startActivity(intent);
    }

    private void parseIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            anchorid = intent.getStringExtra("anchorid");
            albumid = intent.getStringExtra("albumid");
        }
    }

    private void initMeasure() {
        headerHeight = getResources().getDimension(R.dimen.radio_program_banner_height);
        minHeaderHeight = getResources().getDimension(R.dimen.abc_action_bar_default_height_material);
    }

    private void initView() {
        initToolbarHelper();
        getSupportFragmentManager().beginTransaction().replace(R.id.radio_album_program_fm, PlayerToolbarFragment.getInstance()).commit();

        View headerView = View.inflate(getApplicationContext(), R.layout.radio_album_program_header, null);
        radioAlbumProgramAvatarImg = (RoundImageView) headerView.findViewById(R.id.radio_album_program_avatar_img);
        radioAlbumProgramNameTv = (TextView) headerView.findViewById(R.id.radio_album_program_name_tv);
        radioAlbumProgramPlayTimesTv = (TextView) headerView.findViewById(R.id.radio_album_program_play_times_tv);
        radioAlbumProgramFansTv = (TextView) headerView.findViewById(R.id.radio_album_program_fans_tv);
        radioAlbumProgramBannerFollowBtn = (ImageView) headerView.findViewById(R.id.radio_album_program_banner_follow_btn);

        //设置header大小
        radioAlbumList.setHeaderViewSize(ViewGroup.LayoutParams.MATCH_PARENT, (int) headerHeight);
        //设置headerView
        radioAlbumList.getHeaderContainer().addView(headerView);
        radioAlbumList.setHeaderView();
        adapter = new RadioAlbumProgramListAdapter(this);
        radioAlbumList.setAdapter(adapter);
        radioAlbumList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int selectedItemPosition = position - 1;
//                if (mPlayer != null) {
//                    LogUtil.d("playList:" + playList.getSongs().size() + " position" + selectedItemPosition);
//                    mPlayer.play(playList, selectedItemPosition);
//                    currentIndex = selectedItemPosition;
//                    updataListViewSelectState(currentIndex);
//                }
                if (mPlayer != null && playList != null) {
                    if (playList.getSongs().isEmpty()) {
                        //没有播放歌曲
                        LogUtil.d("playList:" + playList.getSongs().size() + " position" + selectedItemPosition);
                        currentIndex = selectedItemPosition;
                        mPlayer.play(playList, currentIndex);
                    } else {
                        //正在播放歌曲
                        if (currentIndex == selectedItemPosition) {
                            //点击的是播放的条目
                            if (mPlayer.isPlaying()) {
                                mPlayer.pause();
                            } else {
                                mPlayer.play();
                            }
                        } else {
                            //点击的不是播放的条目
                            currentIndex = selectedItemPosition;
                            mPlayer.play(playList, currentIndex);
                        }
                    }
                    LogUtil.e("RadioAlbumProgramActivi", "currentIndex:" + currentIndex);
                    updataListViewSelectState(currentIndex);
                }
            }
        });

        radioAlbumList.setOnScrollListener(this);

    }

    private void updateView(RadioAnchorInfo basicinfo, List<Song> programlist) {
        String radiocover = basicinfo.getRadiocover();
        String radioavatar = basicinfo.getRadioavatar();
        String radioname = basicinfo.getRadioname();
        String playcount = basicinfo.getPlaycount();
        String fans = basicinfo.getFans();
        albumname = basicinfo.getAlbumname();
        int follow = basicinfo.getFollow();

        Glide.with(this).load(radiocover).dontAnimate().placeholder(R.drawable.icon_pic_holder).error(R.drawable.icon_radio_top_bg)
                .diskCacheStrategy(DiskCacheStrategy.ALL).into(radioAlbumList.getHeaderView());

        Glide.with(this).load(radioavatar).dontAnimate().placeholder(R.drawable.icon_pic_holder).error(R.drawable.icon_pic_holder)
                .diskCacheStrategy(DiskCacheStrategy.ALL).into(radioAlbumProgramAvatarImg);
        if (!AsStrUtils.isEmpty(radioname)) {
            this.radioname = radioname;
            radioAlbumProgramNameTv.setText(radioname);
        }
        if (!AsStrUtils.isEmpty(playcount)) {
            radioAlbumProgramPlayTimesTv.setText(String.format(getResources().getString(R.string.radio_album_play_times_format), playcount));
        }
        if (!AsStrUtils.isEmpty(fans)) {
            radioAlbumProgramFansTv.setText(String.format(getResources().getString(R.string.radio_album_fans_format), fans));
        }

        if (follow == 1) {
            radioAlbumProgramBannerFollowBtn.setImageResource(R.drawable.icon_radio_album_followed);
        } else {
            radioAlbumProgramBannerFollowBtn.setImageResource(R.drawable.icon_radio_album_unfollow);
        }
        playList.setSongs(programlist);
        adapter.clearAll();
        adapter.appendToList(programlist);

        if (mPlayer != null) {
            updataListViewSelectState(mPlayer.getPlayingSong());
        }

    }

    protected void initToolbarHelper() {
        this.setSupportActionBar(this.toolbar);
        assert getSupportActionBar() != null;
        toolbar.setTitle("");
        getSupportActionBar().setTitle("");
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public void showLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void showErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void loadData(RadioAnchorInfo basicinfo, List<Song> programlist) {
        updateView(basicinfo, programlist);
    }

    @Override
    public void onPlaybackServiceBound(PlaybackService service) {
        mPlayer = service;
    }

    @Override
    public void onPlaybackServiceUnbound() {
        mPlayer = null;
    }

    @Override
    public void onSongUpdated(@Nullable Song song) {
        //绑定服务成功以后去刷新列表中的状态
        if (adapter != null && !adapter.isEmpty()) {
            updataListViewSelectState(song);
        }
    }

    @Override
    public void updatePlayToggle(PlayState change) {
        adapter.setSelectIndex(change);
    }

    @OnClick(R.id.btn_refresh)
    public void onClick() {
        doGetRadioAlbumProgram();
    }

    //刷新选中状态
    public void updataListViewSelectState(Song song) {
        //播放结束
        if (song == null) {
            currentIndex = -1;
            adapter.setSelectIndex(currentIndex, PlayState.STOP);
            return;
        }
        for (int i = 0, j = adapter.getList().size(); i < j; i++) {
            Song radioAlbumProgramData = adapter.getList().get(i);
            if (song.getProgramid().equals(radioAlbumProgramData.getProgramid())) {
                //自动播放
                currentIndex = i;
                if (mPlayer != null) adapter.setSelectIndex(i, mPlayer.getPlayStatus());
                LogUtil.e("currentIndex: " + currentIndex + "; song.getProgramid(): " + song.getProgramid()
                        + "; radioAlbumProgramData.getProgramid(): " + radioAlbumProgramData.getProgramid());
                break;
            }
        }
    }

    //刷新选中状态
    public void updataListViewSelectState(int index) {
        if (mPlayer != null) adapter.setSelectIndex(index, mPlayer.getPlayStatus());
    }

    //刷新播放的状态
    public void updataListViewItemPlayState(PlayState change) {
        if (currentIndex == -1) return;
        adapter.setSelectIndex(change);
    }

    Subscriber subscriberUpdateSong = new Subscriber<Song>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }


        @Override
        public void onNext(Song song) {
            updataListViewSelectState(song);
        }
    };

    Subscriber subscriberPlayState = new Subscriber<PlayState>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }


        @Override
        public void onNext(PlayState change) {
            updataListViewItemPlayState(change);
        }
    };

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
//        if (scrollState == SCROLL_STATE_IDLE) {
//        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        //Y轴偏移量
        float scrollY = getScrollY(view);

        //变化率
        float headerBarOffsetY = headerHeight - minHeaderHeight;//Toolbar与header高度的差值
        float offset = 1 - Math.max((headerBarOffsetY - scrollY) / headerBarOffsetY, 0f);

        //Toolbar背景色透明度
        transparencyAppBarLayout.setBackgroundColor(Color.argb((int) (offset * 255), 255, 255, 255));

        /*** 标题文字处理 ***/
        //判断标题文字的显示
        if (scrollY > headerBarOffsetY) {
            if (albumname != null) {
                //有专辑就显示专辑名
                toolbar.setTitle(albumname);
            } else {
                //全部节目就显示主播名
                if (radioname != null) {
                    toolbar.setTitle(radioname);
                }
            }
        } else {
            toolbar.setTitle("");
        }
    }

    /**
     * 得到ListView在Y轴上的偏移
     */
    public float getScrollY(AbsListView view) {
        View c = view.getChildAt(0);

        if (c == null)
            return 0;

        int firstVisiblePosition = view.getFirstVisiblePosition();
        int top = c.getTop();

        float headerHeight = 0;
        if (firstVisiblePosition >= 1) {
            headerHeight = this.headerHeight;
            StatusBarUtils.from(this)
                    .setTransparentStatusbar(true)//状态栏是否透明
                    .setTransparentNavigationbar(false)//Navigationbar是否透明
                    .setLightStatusBar(true)//状态栏字体是否为亮色
                    .process();
        } else {
            StatusBarUtils.from(this)
                    .setTransparentStatusbar(true)//状态栏是否透明
                    .setTransparentNavigationbar(false)//Navigationbar是否透明
                    .setLightStatusBar(false)//状态栏字体是否为亮色
                    .process();
        }
        return -top + firstVisiblePosition * c.getHeight() + headerHeight;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.detachView();
        RxBus.get().unregister(PlayConstants.ACTION_UPDATA_SONG, observableUpdateSong);
        RxBus.get().unregister(PlayConstants.ACTION_PLAY_STATUS_CHANGED, observablePlayState);
    }
}
